<template>
    <div class="">
        <van-nav-bar title="编辑地址" left-text="返回" left-arrow @click-left="onClickLeft" />
        <van-address-edit :area-list="areaList" show-delete show-search-result :search-result="searchResult"
            :area-columns-placeholder="['请选择', '请选择', '请选择']" :address-info="addressEditModel" @save="onSave"
            @delete="onDelete" @change-detail="onChangeDetail" />
    </div>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router';
import { ref } from 'vue';
import { areaList } from '@vant/area-data';
import { deleteAddress, updateAddress } from '../api/index';
import { showLoadingToast, showSuccessToast, showConfirmDialog } from 'vant';

const router = useRouter();
const route = useRoute();
const address = route.query;
const addressId = route.query.id;

// 定义一个响应式的对象来保存地址编辑组件的状态
const addressEditModel = ref({
    name: address.name || '',
    tel: address.tel || '',
    province: address.province || '',
    city: address.city || '',
    county: address.county || '',
    addressDetail: address.addressDetail || '',
});

const onClickLeft = () => router.back();

// 事件处理函数
const onSave = (address) => {
    // 处理保存地址的逻辑
    console.log('Saved address:', address);
    console.log(addressId);
    updateAddress({
        daId: addressId,
        contactName: address.name,
        contactSex: 1,
        contactTel: address.tel,
        address: address.province + " " + address.city + " " + address.county + " " + address.addressDetail
    })
        .then(function () {
            showLoadingToast({
                message: '修改中...',
                forbidClick: true,
            });
            setTimeout(() => {
                router.push('/setaddress')
                showSuccessToast('修改地址成功');
            }, 1000);
        })
};

const onDelete = () => {
    console.log(addressId)
    showConfirmDialog({
        title: '提醒',
        message:
            '一旦删除就无法找回地址信息，是否确认删除？',
    })
        .then(async () => {
            try {
                const response = await deleteAddress({
                    daId: addressId
                });
                if (response.code == 2000) {
                    showLoadingToast({
                        message: '正在删除地址...',
                        forbidClick: true,
                    });
                    setTimeout(() => {
                        router.push('/setaddress')
                        showSuccessToast('删除地址成功');
                    }, 1000);
                }
                console.log(response);
            } catch (error) {
                console.error('删除地址时出错:', error);
            }
        })
        .catch(() => {
            showSuccessToast('取消删除');
        });

}

const onChangeDetail = (detail) => {
    // 处理详细地址变化的逻辑
    console.log('Address detail changed:', detail);
};
</script>

<style lang="scss" scoped></style>
